package etcd_sdr

import (
	jsoniter "github.com/json-iterator/go"
	"google.golang.org/grpc/resolver"
	"net/url"
	"strings"
)

type ServerInfo struct {
	Namespace *string         `json:"namespace"`
	ID        string          `json:"id"`
	Target    resolver.Target `json:"target"`
}

// NewServerInfo init ServerInfo
func NewServerInfo(id string, nameSpace *string, serverURL string) (*ServerInfo, error) {

	_url, err := url.Parse(serverURL)
	if err != nil {
		return nil, err
	}

	return &ServerInfo{
		Namespace: nameSpace,
		ID:        id,
		Target:    resolver.Target{URL: *_url},
	}, nil
}

func (s *ServerInfo) GetServerInfoKey() string {
	endpoint := s.Target.Endpoint()
	if s.Namespace == nil {
		return strings.TrimSpace(strings.Join([]string{endpoint, s.ID}, "::"))
	}
	return strings.TrimSpace(strings.Join([]string{*s.Namespace, endpoint, s.ID}, "::"))
}

func (s *ServerInfo) GetServerInfoPrefixKey() string {
	return getNamingPrefixKey(s.Namespace, s.Target)
}

func (s *ServerInfo) GetHostAddress() string {
	return s.Target.URL.Host
}

func getNamingPrefixKey(namespace *string, target resolver.Target) string {
	endpoint := target.Endpoint()

	if namespace == nil {
		return strings.TrimSpace(strings.Join([]string{endpoint}, "::"))
	}
	return strings.TrimSpace(strings.Join([]string{*namespace, endpoint}, "::"))
}

func MarshalServerInfo(serverInfo *ServerInfo) (info []byte, err error) {
	info, err = jsoniter.Marshal(serverInfo)
	if err != nil {
		return nil, err
	}
	return info, nil
}

func UnMarshalServerInfo(info []byte) (serverInfo *ServerInfo, err error) {
	err = jsoniter.Unmarshal(info, serverInfo)
	if err != nil {
		return nil, err
	}
	return serverInfo, nil
}
